package com.haibei.view;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.ListUtiles;
import com.common.uitl.LogUtil;
import com.common.uitl.StringUtils;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.activity.MainActivity;
import com.haibei.activity.market.GoodsDetailActivity;
import com.haibei.activity.market.MarketGoodsListActivity;
import com.haibei.adapter.HotGoodsAdapter;
import com.haibei.adapter.bean.Goods;
import com.haibei.adapter.bean.GoodsType;
import com.haibei.adapter.bean.GoodsTypeItem2;
import com.haibei.adapter.bean.GoodsTypeItem2.ClickListener;
import com.haibei.adapter.bean.HotGoodsBanner;
import com.haibei.net.NetInterface;
import com.haibei.view.PullToRefreshView.OnFooterRefreshListener;
import com.haibei.view.PullToRefreshView.OnHeaderRefreshListener;

/**
 * 海淘
 * 
 * @author wangzy
 */
public class SubTabViewMarket extends SubTabView implements View.OnClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {

	// private PullToRefreshView mPullToRefreshView;
	private BaseTask mBaseTask;
	private final int page_size = 10;
	private final int INT_RTYPE_FIRST = 1;
	private final int INT_RTYPE_REFRESH = 2;
	private final int INT_RTYPE_LODMORE = 3;
	private ArrayList<GoodsType> goodsTypes;
	public ArrayList<HotGoodsBanner> hotGods;
	private ViewFlow mViewFlow;
	// public CircleFlowIndicator indic;
	private RelativeLayout mRelativeLayoutHotGoods;

	// 轮播
	// public boolean timeFlag = true;
	// public int gallerypisition = 0;
	// private int positon = 0;
	// public GuideGallery mGuidGallery;
	// public ImageTimerTask timeTaks = null;
	// private Thread timeThread = null;
	// private boolean isExit = false;

	public SubTabViewMarket(MainActivity activity) {
		super(activity);
		hotGods = new ArrayList<HotGoodsBanner>();
	}

	@Override
	public void initView() {
		this.mContentView = View.inflate(mActivity, R.layout.sub_tab_market, null);
		// this.mGuidGallery = (GuideGallery)
		// findViewById(R.id.image_wall_gallery);
		// mPullToRefreshView = (PullToRefreshView)
		// findViewById(R.id.main_pull_refresh_view);
		// mPullToRefreshView.setOnHeaderRefreshListener(this);
		// mPullToRefreshView.setOnFooterRefreshListener(this);
		this.mViewFlow = (ViewFlow) findViewById(R.id.viewflow);
		// this.indic = (CircleFlowIndicator)
		// findViewById(R.id.viewflowindic);// 小点点
		this.mRelativeLayoutHotGoods = (RelativeLayout) findViewById(R.id.relativeLayoutHotGoods);
		// timeTaks = new ImageTimerTask();// 开启轮播
		// Timer autoGallery = new Timer();
		// autoGallery.scheduleAtFixedRate(timeTaks, 5000, 5000);
	}

	@Override
	public void onShow() {
		getActivity().getSlidingMenu().setSlidingEnabled(false);
		if (ListUtiles.isEmpty(goodsTypes)) {
//			 requestParCategory();
//			 requestBanner();
			addGoodType2View(createDefaultGoodsType());
		}
		if (ListUtiles.isEmpty(hotGods)) {
			requestBanner();
		}
		// timeFlag = false;
	}

	private void requestParCategory() {
		HashMap<String, String> hmap = new HashMap<String, String>();
		getListTask().execute(hmap);
	}

	private void requestBanner() {
		HashMap<String, String> hmap = new HashMap<String, String>();
		getListBannerTask().execute(hmap);
	}

	private void buildBanner(ArrayList<HotGoodsBanner> hotsGods) {
		if (mActivity.isFinishing()) {
			return;
		}
		mRelativeLayoutHotGoods.setBackgroundDrawable(null);
		final HotGoodsAdapter hga = new HotGoodsAdapter(getActivity(), hotsGods);
		mViewFlow.setAdapter(hga);
		LinearLayout pointLinear = (LinearLayout) findViewById(R.id.gallery_point_linear);
		pointLinear.setBackgroundColor(Color.argb(200, 135, 135, 152));
		final ArrayList<ImageView> indicatorMiter = new ArrayList<ImageView>();
		for (int i = 0; i < hotsGods.size(); i++) {
			ImageView pointView = new ImageView(mActivity);
			HotGoodsBanner tag = hotsGods.get(i);
			if (i == 0) {
				pointView.setBackgroundResource(R.drawable.feature_point_cur);
			} else {
				pointView.setBackgroundResource(R.drawable.feature_point);
			}
			pointView.setTag(tag);
			indicatorMiter.add(pointView);
			pointLinear.addView(pointView);
		}
		hga.setOnItemClickListener(new HotGoodsAdapter.OnItemClickListener() {
			@Override
			public void onClick(int position, HotGoodsBanner hotb) {
				for (int i = 0, isize = indicatorMiter.size(); i < isize; i++) {
					ImageView imageViewIndicator = indicatorMiter.get(i);
					if (i == position) {
						imageViewIndicator.setBackgroundResource(R.drawable.feature_point_cur);
					} else {
						imageViewIndicator.setBackgroundResource(R.drawable.feature_point);
					}
				}
				String wareId = "";
				HotGoodsBanner hgod = (HotGoodsBanner) hga.getItem(position);
				if (null != hgod) {
					String wareIds = hgod.getWareIds();
					if (!StringUtils.isEmpty(wareIds)) {
						String[] ids = wareIds.split(",");
						wareId = ids[0];
					} else {
						wareId = wareIds;
					}
					Intent intent = new Intent();
					Goods gods = new Goods();
					gods.setId(wareId);
					intent.putExtra("goods", gods);
					intent.setClass(mActivity, GoodsDetailActivity.class);
					mActivity.startActivity(intent);
				}
				LogUtil.e(App.tag, "hot click id:" + wareId);
			}
		});
	}

	private ArrayList<GoodsType> createDefaultGoodsType() {
		ArrayList<GoodsType> goodTypes = new ArrayList<GoodsType>();
		int defaultId = 0;
		GoodsType milkPowder = new GoodsType(true);
		milkPowder.setName("奶粉");
		milkPowder.setId(String.valueOf(++defaultId));
		milkPowder.setIconDefault(R.drawable.bg_default_milk_power);
		milkPowder.setIconSelected(R.drawable.bg_default_milk_power_p);
		goodTypes.add(milkPowder);

		GoodsType secondFod = new GoodsType(true);
		secondFod.setName("辅食");
		secondFod.setId(String.valueOf(++defaultId));
		secondFod.setIconDefault(R.drawable.bg_default_seond_food);
		secondFod.setIconSelected(R.drawable.bg_default_seond_food_p);
		goodTypes.add(secondFod);

		GoodsType cheese = new GoodsType(true);
		cheese.setName("奶酪");
		cheese.setId(String.valueOf(++defaultId));
		cheese.setIconDefault(R.drawable.bg_default_cheese);
		cheese.setIconSelected(R.drawable.bg_default_cheese_p);
		goodTypes.add(cheese);

		GoodsType washMater = new GoodsType(true);
		washMater.setName("洗护用品");
		washMater.setId(String.valueOf(++defaultId));
		washMater.setIconDefault(R.drawable.bg_default_wash_mater);
		washMater.setIconSelected(R.drawable.bg_default_wash_mater_p);
		goodTypes.add(washMater);

		GoodsType nutrition = new GoodsType(true);
		nutrition.setName("营养保健");
		nutrition.setId(String.valueOf(++defaultId));
		nutrition.setIconDefault(R.drawable.bg_default_nutrition);
		nutrition.setIconSelected(R.drawable.bg_default_nutrition_p);
		goodTypes.add(nutrition);

		GoodsType other = new GoodsType(true);
		other.setName("其他");
		other.setId(String.valueOf(++defaultId));
		other.setIconDefault(R.drawable.bg_default_other);
		other.setIconSelected(R.drawable.bg_default_other_p);
		goodTypes.add(other);

		return goodTypes;
	}

	private void addGoodType2View(final ArrayList<GoodsType> googsTypes) {
		if (mActivity.isFinishing()) {
			return;
		}
		final ArrayList<GoodsTypeItem2> goodsTimes = new ArrayList<GoodsTypeItem2>();

		for (GoodsType gtype : googsTypes) {
			GoodsTypeItem2 gitem = new GoodsTypeItem2(getActivity(), gtype);
			goodsTimes.add(gitem);
		}

		LinearLayout l1 = (LinearLayout) findViewById(R.id.linearLayoutType1);
		l1.removeAllViews();
		LinearLayout l2 = (LinearLayout) findViewById(R.id.linearLayoutType2);
		l2.removeAllViews();

		int dw = Tool.getDisplayMetrics(mActivity).x;

//		int rw = (int) (dw - mActivity.getResources().getDimension(R.dimen.margin_micro) - mActivity.getResources().getDimension(R.dimen.pading_content) * 1);

		int rw = (int) (dw - mActivity.getResources().getDimension(R.dimen.margin_micro) );
		int w = rw / 3;
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(w, LayoutParams.WRAP_CONTENT);
		LogUtil.i(App.tag, "lw:" + w);

		for (int i = 0, isize = goodsTimes.size(); i < isize; i++) {
			final GoodsTypeItem2 gtype = goodsTimes.get(i);
			View view = gtype.getView();
			gtype.setClickListener(new ClickListener() {
				@Override
				public void onClick(View rootView, GoodsType gtype) {
					gotoGoodsList(gtype);
				}
			});
//			view.setOnClickListener(new OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					for (GoodsTypeItem temp : goodsTimes) {
//						if (temp.equals(gtype)) {
//							temp.check();
//						} else {
//							temp.unCheck();
//						}
//					}
//					gotoGoodsList(gtype.getGoodsType());
//				}
//			});
			if (i <= 2) {
				l1.addView(view, lp);
			} else {
				l2.addView(view, lp);
			}
		}

	}

	private void gotoGoodsList(GoodsType goodsType) {
		Intent i = new Intent();
		i.setClass(getActivity(), MarketGoodsListActivity.class);
		i.putExtra("goodstype", goodsType);
		getActivity().startActivity(i);
		LogUtil.i(App.tag, "click go:" + goodsType.getName());
	}

	@Override
	public void onClick(View v) {

	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
	}

	//获取分类
	private BaseTask getListTask() {
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				getActivity().showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				getActivity().hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						ArrayList<GoodsType> typelist = (ArrayList<GoodsType>) result.getData()[0];
						goodsTypes = typelist;
						addGoodType2View(typelist);
					} else {
						Tool.ToastShow(getActivity(), result.getMessage());
					}
				} else {
					Tool.ToastShow(getActivity(), R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.listParCategory(getActivity(), paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	//获取热门商品
	private BaseTask getListBannerTask() {
		mBaseTask = new BaseTask(new NetCallBack() {

			@Override
			public void onFinish(NetResult result) {
				if (null != result) {
					if (result.isSuccess()) {
						hotGods = (ArrayList<HotGoodsBanner>) result.getData()[0];
						if (!ListUtiles.isEmpty(hotGods)) {
							buildBanner(hotGods);
						}
						// if (ListUtiles.isEmpty(hotGods)) {
						// indic.setVisibility(View.INVISIBLE);
						// } else {
						// buildBanner(hotGods);
						// indic.setVisibility(View.VISIBLE);
						// }
					} else {
						// indic.setVisibility(View.INVISIBLE);
					}
				} else {
					// Tool.ToastShow(getActivity(), R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.listBanner(getActivity(), paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	// =====广告轮播开始=========

	// public void changePointView(int cur) {
	// LinearLayout pointLinear = (LinearLayout)
	// findViewById(R.id.gallery_point_linear);
	// View view = pointLinear.getChildAt(positon);
	// View curView = pointLinear.getChildAt(cur);
	// if (view != null && curView != null) {
	// ImageView pointView = (ImageView) view;
	// ImageView curPointView = (ImageView) curView;
	// pointView.setBackgroundResource(R.drawable.feature_point);
	// curPointView.setBackgroundResource(R.drawable.feature_point_cur);
	// positon = cur;
	// }
	// }
	//
	// final Handler autoGalleryHandler = new Handler() {
	// public void handleMessage(Message message) {
	// super.handleMessage(message);
	// switch (message.what) {
	// case 1:
	// mGuidGallery.setSelection(message.getData().getInt("pos"));
	// break;
	// }
	// }
	// };
	//
	// public class ImageTimerTask extends TimerTask {
	// public volatile boolean timeCondition = true;
	//
	// public void run() {
	// synchronized (this) {
	// while (!timeCondition) {
	// try {
	// Thread.sleep(100);
	// wait();
	// } catch (InterruptedException e) {
	// Thread.interrupted();
	// }
	// }
	// }
	// try {
	// gallerypisition = mGuidGallery.getSelectedItemPosition() + 1;
	// Message msg = new Message();
	// Bundle date = new Bundle();
	// date.putInt("pos", gallerypisition);
	// msg.setData(date);
	// msg.what = 1;//
	// autoGalleryHandler.sendMessage(msg);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	// }

}
